/**
 * uniapp API 封装
 * 统一管理uniapp的API调用，避免直接使用uni.xxx
 */

/**
 * 工具函数
 */
// 构建完整URL
const buildUrl = (url, query = {}) => {
	// 如果url已经是完整URL，直接返回
	if (url.startsWith('http://') || url.startsWith('https://')) {
		return url
	}
	
	// 处理查询参数
	let queryString = ''
	if (Object.keys(query).length > 0) {
		queryString = '?' + Object.keys(query)
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
			.join('&')
	}
	
	// 确保url以/开头
	if (!url.startsWith('/')) {
		url = '/' + url
	}
	
	return url + queryString
}

/**
 * 页面跳转相关
 */
// 页面导航
export const navigateTo = (url, query = {}) => {
	return new Promise((resolve, reject) => {
		// 构建完整的URL
		const fullUrl = buildUrl(url, query)
		
		// 判断平台
		// #ifdef H5
		// H5环境下使用window.location
		window.location.href = fullUrl
		resolve()
		// #endif
		
		// #ifdef MP-WEIXIN || APP-PLUS
		// 小程序和App环境下使用uni.navigateTo
		uni.navigateTo({
			url: fullUrl,
			success: () => resolve(),
			fail: (err) => {
				console.error('navigateTo失败:', fullUrl, err)
				reject(err)
			}
		})
		// #endif
	})
}

// 页面重定向
export const redirectTo = (url, query = {}) => {
	return new Promise((resolve, reject) => {
		const fullUrl = buildUrl(url, query)
		
		// #ifdef H5
		window.location.replace(fullUrl)
		resolve()
		// #endif
		
		// #ifdef MP-WEIXIN || APP-PLUS
		uni.redirectTo({
			url: fullUrl,
			success: () => resolve(),
			fail: (err) => {
				console.error('redirectTo失败:', fullUrl, err)
				reject(err)
			}
		})
		// #endif
	})
}

// 切换Tab
export const switchTab = (url) => {
	return new Promise((resolve, reject) => {
		// #ifdef H5
		window.location.href = url
		resolve()
		// #endif
		
		// #ifdef MP-WEIXIN || APP-PLUS
		uni.switchTab({
			url: url,
			success: () => resolve(),
			fail: (err) => {
				console.error('switchTab失败:', url, err)
				reject(err)
			}
		})
		// #endif
	})
}

// 返回上一页
export const navigateBack = (delta = 1) => {
	return new Promise((resolve, reject) => {
		// #ifdef H5
		window.history.back()
		resolve()
		// #endif
		
		// #ifdef MP-WEIXIN || APP-PLUS
		uni.navigateBack({
			delta: delta,
			success: () => resolve(),
			fail: (err) => {
				console.error('navigateBack失败:', err)
				reject(err)
			}
		})
		// #endif
	})
}

/**
 * 数据存储相关
 */
// 存储数据
export const setStorage = (key, data) => {
	if (typeof data === 'object') {
		data = JSON.stringify(data);
	}
	try {
		uni.setStorageSync(key, data);
		return true;
	} catch (e) {
		console.error('setStorage失败:', e);
		return false;
	}
};

// 获取数据
export const getStorage = (key, defaultValue = null) => {
	try {
		const value = uni.getStorageSync(key);
		if (value === '' || value === undefined || value === null) {
			return defaultValue;
		}
		try {
			// 尝试解析JSON
			return JSON.parse(value);
		} catch (e) {
			// 不是JSON格式，直接返回
			return value;
		}
	} catch (e) {
		console.error('getStorage失败:', e);
		return defaultValue;
	}
};

// 删除数据
export const removeStorage = (key) => {
	try {
		uni.removeStorageSync(key);
		return true;
	} catch (e) {
		console.error('removeStorage失败:', e);
		return false;
	}
};

// 清空所有数据
export const clearStorage = () => {
	try {
		uni.clearStorageSync();
		return true;
	} catch (e) {
		console.error('clearStorage失败:', e);
		return false;
	}
};

/**
 * 提示相关
 */
// 显示消息提示框
export const showToast = (title, icon = 'none', duration = 1500) => {
	return new Promise((resolve) => {
		uni.showToast({
			title,
			icon,
			duration,
			success: resolve
		});
	});
};

// 显示加载提示框
export const showLoading = (title = '加载中...', mask = true) => {
	uni.showLoading({
		title,
		mask
	});
};

// 隐藏加载提示框
export const hideLoading = () => {
	uni.hideLoading();
};

// 显示模态弹窗
export const showModal = (options = {}) => {
	const defaultOptions = {
		title: '提示',
		content: '',
		showCancel: true,
		cancelText: '取消',
		confirmText: '确定',
		confirmColor: '#fa436a'
	};
	const mergedOptions = { ...defaultOptions, ...options };

	return new Promise((resolve, reject) => {
		uni.showModal({
			...mergedOptions,
			success: (res) => {
				if (res.confirm) {
					resolve(true);
				} else if (res.cancel) {
					resolve(false);
				} else {
					reject(new Error('未知结果'));
				}
			},
			fail: reject
		});
	});
};

/**
 * 设备相关
 */
// 获取系统信息
export const getSystemInfo = () => {
	return new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success: resolve,
			fail: reject
		});
	});
};

// 振动
export const vibrate = (isLong = false) => {
	return new Promise((resolve, reject) => {
		const method = isLong ? 'vibrateLong' : 'vibrateShort';
		uni[method]({
			success: resolve,
			fail: reject
		});
	});
};

/**
 * 扫码相关
 */
// 扫描二维码
export const scanCode = (onlyFromCamera = true, scanType = ['qrCode']) => {
	return new Promise((resolve, reject) => {
		uni.scanCode({
			onlyFromCamera,
			scanType,
			success: resolve,
			fail: reject
		});
	});
};

/**
 * 其他工具
 */
// 格式化金额
export const formatMoney = (value, decimals = 2) => {
	if (isNaN(value) || value === null) return '0.00';
	return parseFloat(value).toFixed(decimals);
};

// 创建唯一ID
export const createUniqueId = () => {
	return 'id_' + Math.random().toString(36).substr(2, 9);
};

export default {
	navigateTo,
	redirectTo,
	switchTab,
	navigateBack,
	setStorage,
	getStorage,
	removeStorage,
	clearStorage,
	showToast,
	showLoading,
	hideLoading,
	showModal,
	getSystemInfo,
	vibrate,
	scanCode,
	formatMoney,
	createUniqueId
}; 